﻿using System;
using System.Collections;
using System.Windows;
using System.Windows.Threading;
using PeoplesJukebox.Web.Enums;
using PeoplesJukebox.Web.ServiceClients.Bases;

namespace PeoplesJukebox.Web.Pages
{
    /// <summary>
    /// Application home page
    /// </summary>
    /// <remarks>
    /// Uses a timer to poll the player service, to update the
    /// "now playing" track details
    /// </remarks>
    public partial class HomePage : PageBase
    {
        private DispatcherTimer PollTimer { get; set; }

        /// <summary>
        /// Returns the page type
        /// </summary>
        public override PageType PageType
        {
            get { return PageType.Home; }
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public HomePage()
        {
            InitializeComponent();
            this.PlayerServiceClient.SearchComplete += new ServiceClientBase.SearchCompleteEventHandler(PlayerServiceClient_SearchComplete);
            this.PollTimer = new DispatcherTimer();
            this.PollTimer.Interval = new TimeSpan(0, 0, 5);
            this.PollTimer.Tick += new EventHandler(PollTimer_Tick);
            this.PollTimer.Start();
            this.PlayerServiceClient.GetCurrentTrack();
        }

        /// <summary>
        /// Resets page state
        /// </summary>
        public override void Reset()
        {
            this.PollTimer.Start();
        }

        private void PlayerServiceClient_SearchComplete(System.Collections.IEnumerable results)
        {
            //this returns the "now playing" track:
            if (results != null)
            {
                IEnumerator enumerator = results.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    this.nowPlaying.DataContext = enumerator.Current;
                    this.nowPlaying.Visibility = Visibility.Visible;
                }
            }
        }

        private void PollTimer_Tick(object sender, EventArgs e)
        {
            this.PlayerServiceClient.GetCurrentTrack();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.PlayerServiceClient.CancelRequest();
            this.PollTimer.Stop();
            this.Completed(PageType.Select);
        }
    }
}